package com.xmjs.baselibrary.broadcast;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import com.xmjs.baselibrary.utils.enums.NetworkStatus;

import static com.xmjs.baselibrary.utils.enums.NetworkStatus.NETWORK_MOBILE;
import static com.xmjs.baselibrary.utils.enums.NetworkStatus.NETWORK_NONE;
import static com.xmjs.baselibrary.utils.enums.NetworkStatus.NETWORK_WIFI;

/**
 * 监听网络状态的广播
 */
public class NetBroadcastReceiver extends BroadcastReceiver {
    OnNetworkListener listener;

    public NetBroadcastReceiver() {

    }

    public NetBroadcastReceiver(OnNetworkListener listener) {
        this.listener = listener;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
            try {
                NetworkStatus status = getNetWorkState(context);
                if (listener != null)
                    listener.onNetChange(status);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public interface OnNetworkListener {
        //网络状态发生变化的回调
        void onNetChange(NetworkStatus status);
    }

    public NetworkStatus getNetWorkState(Context context) {
        //得到连接管理器对象
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        if (activeNetworkInfo != null && activeNetworkInfo.isConnected()) {
            if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                return NETWORK_WIFI;//切换到wifi网络
            } else if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                return NETWORK_MOBILE;//切换到数据网络
            }
        } else {
            return NETWORK_NONE;//断网
        }
        return NETWORK_NONE;//断网
    }
}
